# -*- coding: utf-8 -*-
from pymongo import UpdateOne
from zc_core.client.mongo_client import Mongo
from zc_core.util.encrypt_util import md5
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.pipelines.catalog import CatalogHelper
from huiemall.matcher import match_sp_sku_id_from_img


def update_status(year):
    collection = 'data_20200514'
    mongo = Mongo(year=year)
    bulk_list = list()
    items = mongo.list(collection, fields={'_id': 1, 'skuName': 1}, query={'spuId': None})
    for item in items:
        sku_name = item.get('skuName')
        spu_id = md5(sku_name)
        item['spuId'] = spu_id
        bulk_list.append(UpdateOne({'_id': item.get('_id')}, {'$set': item}, upsert=False))

    print(len(bulk_list))
    if bulk_list:
        mongo.bulk_write(collection, bulk_list)


# 从catalog_pool池子修补全部分类
def fix_sku_pool_catalog():
    update_bulk = list()
    mongo = Mongo()
    cat_helper = CatalogHelper()
    src_list = mongo.list('data_20210815', fields={'_id': 1, 'catalog3Id': 1})
    for item in src_list:
        _id = item.get('_id')
        catalog3Id = item.get('catalog3Id')
        dict1 = {}
        dict1['_id'] = _id
        dict1['catalog3Id'] = catalog3Id
        if catalog3Id:
            try:
                cat_helper.fill(dict1)
                update_bulk.append(UpdateOne({'_id': _id}, {'$set': dict1}, upsert=False))
            except Exception as e:
                print(e)
    print(len(update_bulk))
    mongo.bulk_write('data_20210815', update_bulk)
    list1 = mongo.list('data_20210815', query={"catalog1Id": {"$exists": False}}, fields={'_id': 1, 'catalog3Id': 1})
    print('剩余未有分类不完整的数量', len(list1))
    mongo.close()
    print('任务完成~')


def fix_data():
    update_bulk = list()
    mongo = Mongo()
    src_list = mongo.list('data_20210815',
                          fields={'_id': 1, 'brandModel': 1, 'extension': 1, 'materialCode': 1, 'supplierSkuCode': 1,
                                  'supplierSkuId': 1, 'supplierSkuLink': 1})
    for item in src_list:
        _id = item.get('_id')
        dict1 = {}
        dict1['_id'] = _id
        dict1['brandModel'] = item.get('brandModel')
        dict1['extension'] = item.get('extension')
        dict1['materialCode'] = item.get('materialCode')
        dict1['supplierSkuCode'] = item.get('supplierSkuCode')
        dict1['supplierSkuId'] = item.get('supplierSkuId')
        dict1['supplierSkuLink'] = item.get('supplierSkuLink')
        update_bulk.append(UpdateOne({'_id': _id}, {'$set': dict1}, upsert=False))
    print(len(update_bulk))
    mongo.bulk_write('data_20210811', update_bulk)
    mongo.close()
    print('任务完成~')


if __name__ == '__main__':
    # update_status(2020)
    # fix_sku_pool_catalog()
    fix_data()
